package com.ctlele.team.space.widget.toast;

import android.content.Context;
import android.os.Handler;
import android.os.Looper;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import com.ctlele.team.space.R;

public class IToast {

    private static final int ICON_SUCCESS = R.mipmap.success;

    private static final int ICON_FAILED = R.mipmap.failed;

    private static final int ICON_ALERT = R.mipmap.alert_single;

    private static final Handler handler = new Handler(Looper.getMainLooper());

    public static void show(Context context, String msg, int icon) {
        View view = setContent(context, msg, icon);
        showToast(context, view);
    }

    public static IToast success(Context context, String msg) {
        View view = setContent(context, msg, ICON_SUCCESS);
        return showToast(context, view);
    }

    public static IToast fail(Context context, String msg) {
        View view = setContent(context, msg, ICON_FAILED);
        return showToast(context, view);
    }

    public static IToast alert(Context context, String msg) {
        View view = setContent(context, msg, ICON_ALERT);
        return showToast(context, view);
    }

    private static View setContent(Context context, String msg, int icon) {
        View view = LayoutInflater.from(context).inflate(R.layout.dialog_msg_layout, null);
        TextView msgView = view.findViewById(R.id.msg);
        ImageView iconView = view.findViewById(R.id.msg_icon);

        msgView.setText(msg);
        iconView.setImageResource(icon);

        return view;
    }

    private static IToast showToast(Context context, View view) {
        IToast iToast = new IToast();
        handler.post(() -> {
            Toast toast = new Toast(context);
            toast.setGravity(Gravity.CENTER_HORIZONTAL | Gravity.TOP, 0, 0);
            toast.setDuration(Toast.LENGTH_SHORT);
            toast.setView(view);
            toast.show();
        });
        return iToast;
    }

    public void andOnUiThread(Runnable runnable) {
        handler.post(runnable);
    }
}
